import './childAccount.less';
import os from '@packages/lib-os';
import { execWxJob } from '../util';

// 子账号退出
function logout(successCallback) {
    const API = WPT.Util.handleApi('/v1.0/subaccount/to-logout-l');
    WPT.getData(API, ({ code, msg }) => {
        if (code == 0) {
            successCallback && successCallback();
            // 成功退出子账号
            WPT.Modal.loading('系统提示<br>子账号成功登出', {
                time: 1000,
                callback() {
                    window.location.href = '/';
                },
            });
        } else if (code == 935) {
            // 没有登录子账号，无法访问
            WPT.Modal.loading(msg, {
                time: 1000,
                callback() {
                    window.location.href = '/scope/login';
                },
            });
        } else {
            // 其他错误
            WPT.Modal.alert(msg);
        }
    });
}

// 判断是否登录子账号
if (WPT.userinfo && WPT.userinfo.isChildLogin) {
    const loginObj = $(
        `<div class='wptLogin'>正在管理 ﹃ ${WPT.userinfo.nickname.substr(
            0,
            6
        )}﹄<span class='logout'>登 出</span></div>`
    );
    loginObj.find('.logout').on('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        WPT.Modal.confirm('您确认要登出子账号？', () => {
            const { wptChildAccountLogout } = window;
            // app子账号退出
            logout(() => {
                if (typeof wptChildAccountLogout === 'function') {
                    wptChildAccountLogout(
                        {
                            code: 0,
                            msg: 'success',
                        },
                        () => {}
                    );
                }
            });
        });
    });

    // 微信小程序不显示子账号退出
    new Promise((res) => {
        if (os.wechat) {
            execWxJob(() => {
                res(os.xcx);
            });
        } else {
            res(false);
        }
    }).then((isXcx) => {
        !isXcx && $('body').append(loginObj);
    });
}
